<template>
  <div class="fish-grid-container">
    <div class="fish-grid-filter">
      <div class="fish-grid-search">
        <el-input
          v-model="searchQuery"
          placeholder="搜索观赏鱼..."
          :prefix-icon="Search"
          clearable
          @clear="handleSearch"
          @input="handleSearch"
          class="fish-grid-search-input"
        />
      </div>
      <div class="fish-grid-categories">
        <span
          v-for="category in categories"
          :key="category.id"
          class="fish-grid-category"
          :class="{ active: selectedCategory === category.id }"
          @click="selectCategory(category.id)"
        >
          {{ category.name }}
        </span>
      </div>
    </div>

    <div v-if="loading" class="fish-grid-loading">
      <el-skeleton :rows="3" animated />
      <el-skeleton :rows="3" animated />
      <el-skeleton :rows="3" animated />
    </div>

    <transition-group name="fish-grid" tag="div" class="fish-grid" v-else>
      <div v-for="fish in displayedFishes" :key="fish.id" class="fish-grid-item">
        <FishCard :fish="fish" @click="handleFishClick" />
      </div>
    </transition-group>

    <div v-if="displayedFishes.length === 0 && !loading" class="fish-grid-empty">
      <img src="@/assets/figma-images/figma-blue.svg" alt="没有结果" class="fish-grid-empty-icon" />
      <p>没有找到匹配的观赏鱼</p>
    </div>

    <div class="fish-grid-pagination">
      <el-pagination
        v-if="displayedFishes.length > 0"
        background
        layout="prev, pager, next"
        :total="totalItems"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, onMounted } from 'vue';
  import { Search } from '@element-plus/icons-vue';
  import FishCard from '@/components/FishCard/index.vue';
  import { useRouter } from 'vue-router';

  interface Fish {
    id: string;
    name: string;
    description: string;
    image: string;
    price: number;
    tags: string[];
    categoryId: string;
    isBookmarked?: boolean;
  }

  interface Category {
    id: string;
    name: string;
  }

  // 模拟数据，实际项目中应从API获取
  const categories = ref<Category[]>([
    { id: 'all', name: '全部' },
    { id: 'freshwater', name: '淡水鱼' },
    { id: 'saltwater', name: '海水鱼' },
    { id: 'coldwater', name: '冷水鱼' },
    { id: 'tropical', name: '热带鱼' },
  ]);

  const allFishes = ref<Fish[]>([]);
  const loading = ref(true);
  const searchQuery = ref('');
  const selectedCategory = ref('all');
  const currentPage = ref(1);
  const pageSize = ref(8);
  const router = useRouter();

  // 模拟数据加载
  onMounted(async () => {
    loading.value = true;
    // 模拟API请求延迟
    setTimeout(() => {
      // 模拟数据
      allFishes.value = Array.from({ length: 20 }, (_, index) => ({
        id: `fish-${index + 1}`,
        name: `观赏鱼 ${index + 1}`,
        description: '这是一种美丽的观赏鱼，它拥有鲜艳的色彩和优雅的游姿。适合家庭水族箱饲养。',
        image: `https://picsum.photos/500/300?random=${index + 1}`,
        price: Math.floor(Math.random() * 1000) + 100,
        tags: ['热带', '和平', '容易饲养'].slice(0, Math.floor(Math.random() * 3) + 1),
        categoryId: ['freshwater', 'saltwater', 'coldwater', 'tropical'][Math.floor(Math.random() * 4)],
        isBookmarked: Math.random() > 0.7,
      }));
      loading.value = false;
    }, 1000);
  });

  // 根据搜索和筛选条件过滤鱼类
  const filteredFishes = computed(() => {
    return allFishes.value.filter((fish) => {
      const matchesSearch =
        searchQuery.value === '' ||
        fish.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
        fish.description.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
        fish.tags.some((tag) => tag.toLowerCase().includes(searchQuery.value.toLowerCase()));

      const matchesCategory = selectedCategory.value === 'all' || fish.categoryId === selectedCategory.value;

      return matchesSearch && matchesCategory;
    });
  });

  // 分页后的鱼类
  const displayedFishes = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    return filteredFishes.value.slice(start, end);
  });

  // 总项目数
  const totalItems = computed(() => filteredFishes.value.length);

  // 处理搜索
  const handleSearch = () => {
    currentPage.value = 1;
  };

  // 处理类别选择
  const selectCategory = (categoryId: string) => {
    selectedCategory.value = categoryId;
    currentPage.value = 1;
  };

  // 处理分页变化
  const handlePageChange = (page: number) => {
    currentPage.value = page;
  };

  // 处理鱼类点击
  const handleFishClick = (fish: Fish) => {
    router.push(`/fish/detail/${fish.id}`);
  };
</script>

<style lang="less" scoped>
  .fish-grid-container {
    padding: 20px 0;
  }

  .fish-grid-filter {
    margin-bottom: 30px;
  }

  .fish-grid-search {
    margin-bottom: 20px;
    max-width: 500px;

    &-input {
      :deep(.el-input__wrapper) {
        background-color: #f5f7fa;
        border-radius: 20px;
        box-shadow: 0 2px 12px 0 rgb(0 0 0 / 5%);
        transition: all 0.3s ease;

        &:hover,
        &:focus-within {
          background-color: #fff;
          box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
        }
      }

      :deep(.el-input__inner) {
        padding-left: 20px;
        color: #403a7a;
        font-size: 16px;

        &::placeholder {
          color: #909399;
        }
      }

      :deep(.el-input__prefix-inner) {
        color: #403a7a;
      }

      :deep(.el-input__clear) {
        color: #909399;

        &:hover {
          color: #403a7a;
        }
      }
    }
  }

  .fish-grid-categories {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-bottom: 20px;
  }

  .fish-grid-category {
    padding: 8px 16px;
    border-radius: 20px;
    background-color: #e2f3fe;
    color: #403a7a;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      background-color: #d0ebfd;
    }

    &.active {
      background-color: #403a7a;
      color: white;
    }
  }

  .fish-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 30px;
  }

  .fish-grid-item {
    transition: all 0.5s ease;
  }

  .fish-grid-enter-active,
  .fish-grid-leave-active {
    transition:
      opacity 0.5s ease,
      transform 0.5s ease;
  }

  .fish-grid-enter-from,
  .fish-grid-leave-to {
    opacity: 0;
    transform: translateY(30px);
  }

  .fish-grid-empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 50px 0;
    color: #666;

    &-icon {
      width: 80px;
      height: 80px;
      margin-bottom: 20px;
      opacity: 0.6;
    }
  }

  .fish-grid-pagination {
    margin-top: 40px;
    display: flex;
    justify-content: center;

    :deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
      background-color: #403a7a;
    }
  }

  .fish-grid-loading {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 30px;
  }
</style>
